package com.gagakuai.infrastructure.utils;

import org.apache.flink.api.java.utils.ParameterTool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * @description:
 * @author: houhong
 * @create: 2024-09-07 20:47
 **/
public final class MysqlUtil {

    private static Connection connection = null;

    private static PreparedStatement preparedStatement = null;

    /*
     * description: 初始化 jdbc Connection
     *
     */
    public static Connection init(ParameterTool parameterTool) {

        String _url = parameterTool.get(ParameterConstantsUtil.Mysql_URL);
        String _username = parameterTool.get(ParameterConstantsUtil.Mysql_USERNAME);
        String _passwd = parameterTool.get(ParameterConstantsUtil.Mysql_PASSWD);

        try {
            connection = DriverManager.getConnection(_url, _username, _passwd);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * description: 生成 PreparedStatement
     *
     * @param sql:
     * @return java.sql.PreparedStatement
     */
    public static PreparedStatement initPreparedStatement(String sql) {
        try {
            preparedStatement = connection.prepareStatement(sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return preparedStatement;
    }


    /**
     * 根据参数生成MySQL的DDL语句
     * @param parameterTool 参数工具，用于获取MySQL连接信息
     * @param tableName 要创建的表名
     * @param ddlFieldString 表字段的DDL语句
     * @return 生成的完整的MySQL DDL语句
     */
    public static String buildMysqlDDL(ParameterTool parameterTool, String tableName, String ddlFieldString) {

        // 从参数工具中获取mysql连接的url
        String url = parameterTool.get(ParameterConstantsUtil.Mysql_URL);
        // 从参数工具中获取mysql连接的用户名
        String username = parameterTool.get(ParameterConstantsUtil.Mysql_USERNAME);
        // 从参数工具中获取mysql连接的密码
        String passwd = parameterTool.get(ParameterConstantsUtil.Mysql_PASSWD);
        // 从参数工具中获取MySQL的驱动程序
        String driver = parameterTool.get(ParameterConstantsUtil.Mysql_DRIVER);

        //返回完整的DDL语句
        return  "" +
                "CREATE TABLE IF NOT EXISTS " +
                tableName +
                " (\n" +
                ddlFieldString +
                ")" +
                " WITH (\n" +
                "'connector' = 'jdbc',\n" +
                "'driver' = '" + driver + "',\n" +
                "'url' = '" + url + "',\n" +
                "'username' = '" + username + "',\n" +
                "'password' = '" + passwd + "',\n" +
                "'table-name' = '" + tableName + "'\n" +
                ")";
    }


}
